<template>
  <div class="report-submit-container-padding">
    <TopicSelect v-model="topicId" @change="topicChange" />
    <el-form
      v-if="topicId"
      label-width="auto"
      class="demo-ruleForm"
      style="margin-top: 20px"
    >
      <el-form-item label="上报单位:">
        <el-select
          v-model="ruleForm.reportUnitIds"
          multiple
          placeholder="请选择"
        >
          <el-option
            v-for="item in depts"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="上报人:">
        <el-select v-model="ruleForm.reporterIds" multiple placeholder="请选择">
          <el-option
            v-for="item in users"
            :key="item.id"
            :label="item.nickname"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <component :is="type == 1 ? DevForm : ExtendForm" ref="componentRef" />
    <CommonFooterBar>
      <el-button :loading="loading" @click="handleSubmit">保存为草稿</el-button>
      <el-button type="primary" :loading="loading" @click="handleSubmit(2)">
        确认提交
      </el-button>
    </CommonFooterBar>
  </div>
</template>

<script setup>
  import TopicSelect from '@/components/topicSelect'
  import DevForm from './components/devForm'
  import ExtendForm from './components/ExtendForm'
  import CommonFooterBar from '@/components/commonFooterBar.vue'
  import { getAllUser } from '@/api/system/user'
  import {
    topicOpenCreate,
    topicOpenGet,
    topicOpenUpdate,
  } from '@/api/project/approval/report'
  import { getDeptPage } from '@/api/system/dept/index'
  import { useCloseTabNavigate } from '@/utils/useCloseTabNavigate'
  import { postDraftBoxCreate } from '@/api/project/drafts'
  import '@wangeditor/editor/dist/css/style.css'

  const { closeTabNavigate } = useCloseTabNavigate()

  const $baseMessage = inject('$baseMessage')
  const route = useRoute()

  const topicId = ref('')
  const type = ref(1)

  const ruleForm = reactive({
    reporterIds: [],
    reportUnitIds: [],
  })

  const users = ref([])
  const depts = ref([])
  const detailData = ref({})

  const componentRef = ref()

  const loading = ref(false)

  const topicChange = (value) => {
    type.value = value.type == 1 ? 1 : 2
  }

  const getUserList = () => {
    getAllUser().then((res) => {
      if (res.code == 0 || res.code == 200) {
        users.value = res.data || []
      }
    })
  }

  const getDepts = () => {
    getDeptPage().then((res) => {
      if (res.code == 0 || res.code == 200) {
        depts.value = res.data || []
      }
    })
  }

  const initFormData = () => {
    const getType = route.query.getType || 2
    topicOpenGet({ id: route.query.id, getType: route.query.getType }).then(
      (res) => {
        if (res.code == 0 || res.code == 200) {
          detailData.value = res.data
          topicId.value = detailData.value.baseInfo.topicId
          ruleForm.reportUnitIds =
            getType == 2
              ? detailData.value.baseInfo.reportUnitIds
              : detailData.value.reportUnitIds
          ruleForm.reporterIds =
            getType == 2
              ? detailData.value.baseInfo.reporterIds
              : detailData.value.reporterIds
          type.value = detailData.value.baseInfo.openingType
          nextTick(() => {
            componentRef.value.setFormData(detailData.value)
          })
        }
      }
    )
  }

  const handleSubmit = (saveType = 1) => {
    if (!topicId.value) {
      return $baseMessage('请选择课程', 'error')
    }
    for (const key in ruleForm) {
      if (!ruleForm[key].length) {
        $baseMessage('请填写上报信息', 'error')
        return false
      }
    }
    const params = componentRef.value.getFormData()
    if (!params) {
      return
    }

    const FormData = {
      baseInfo: {},
      ...params,
      ...ruleForm,
      openingType: type.value,
      topicId: topicId.value,
    }

    for (const key in FormData) {
      if (
        ![
          'schedulePlanInfo',
          'budgetAndDetailVO',
          'mainMembers',
          'expertIds',
          'baseInfo',
          'reporterIds',
          'reportUnitIds',
        ].includes(key)
      ) {
        FormData.baseInfo[key] = FormData[key]
        delete FormData[key]
      }
    }

    loading.value = true

    if (saveType == 2) {
      const api =
        route.query.id && route.query?.getType == 2
          ? topicOpenUpdate
          : topicOpenCreate
      if (route.query?.getType == 1) {
        FormData.draftBoxId = route.query.id
      }
      if (route.query?.getType == 2) {
        FormData.baseInfo.id = route.query.id
      }
      api(FormData)
        .then((res) => {
          if (res.code == 0 || res.code == 200) {
            $baseMessage('上报成功')
            closeTabNavigate({ name: 'ProjectApprovalReport' })
          }
        })
        .finally(() => {
          loading.value = false
        })
    } else {
      const formData = {
        id: route.query?.getType == 1 ? route.query.id : '',
        type: 'OPENING',
        submitJson: JSON.stringify({
          ...FormData,
          draftBoxId: route.query?.getType == 1 ? route.query.id : '',
        }),
      }
      postDraftBoxCreate(formData)
        .then((res) => {
          if (res.code == 0 || res.code == 200) {
            $baseMessage('保存草稿成功')
            closeTabNavigate({ name: 'ProjectApprovalReport' })
          }
        })
        .finally(() => {
          loading.value = false
        })
    }
  }

  getUserList()
  getDepts()
  route.query.id && initFormData()
</script>

<style lang="scss" scoped>
  .report-submit-container-padding {
    padding-bottom: 80px !important;
  }
</style>
